<?PHP
define("SYSTEM_MESSAGE",0);
define("USER_MESSAGE",1);
define("ADMIN_MESSAGE",2);

class AdminMessageBO extends BusinessObject{
  
  /* private function using in constructors*/ 
  function setAttributes(){
    $this->fields   = array(
                     'id'        =>   'admin_messages_id',  
                     'sender_id' =>   'admin_messages_sender_id',
                     'admin_id'  =>   'admin_messages_admin_id',
                     'date'      =>   'admin_messages_date',
                     'subject'   =>   'admin_messages_subject',
                     'text'      =>   'admin_messages_text',
                     'view'      =>   'admin_messages_view',  
                     'type'      =>   'admin_messages_type',
                     'attached'  =>   'admin_messages_attached');

    $a = new AdminBO();                       
//    $u = new UserBO();                       
    $this->relations = array("{$a->tableName}" =>"{$a->tableName}.{$a->fields[id]} = {$this->tableName}.{$this->fields[sender_id]}"/*,
                             "{$u->tableName}" =>"{$u->tableName}.{$u->fields[id]} = {$this->tableName}.{$this->fields[sender_id]}"*/);
                            
    BusinessObject::setAttributes();
  }  
  /* constructor */
  function AdminMessageBO(){
    /** super(tableName) */
    BusinessObject::BusinessObject("admin_messages");
    $this->setAttributes();
  }
  /*  Send message*/
  function SendMessages($adminIDs,$subject,$text,$sender_id,$type,$attached){
    $a = new AdminBO();
    $a->id = $adminIDs;
    $query = "INSERT INTO {$this->tableName} (`{$this->fields[admin_id]}`,`{$this->fields[subject]}`,`{$this->fields[text]}`,`{$this->fields[sender_id]}`,`{$this->fields[type]}`,`{$this->fields[date]}`,`{$this->fields[attached]}`)". 
             "SELECT {$a->fields[id]},'$subject','$text','$sender_id','$type',NOW(),'$attached' FROM {$a->tableName} ".$a->getWhere();
    return ($this->ExecuteQuery($query));
  }
  
  function Delete($isAll = true,$where=""){
    /* Check and Delete Attached Files */
    $am = new AdminMessageBO();
    $am->id = $this->id;
    $am->Load(0,0,"","TRIM({$am->fields[attached]})<>''");
    while($am->Next()){
      $amc = new AdminMessageBO();
      $amc->attached = $am->attached;
      if($amc->getCount("{$amc->fields[id]}<>'{$am->id}'")==0){
        unlink(PROJECT_ROOT.'attached/'.$amc->attached);
        rmdir(PROJECT_ROOT.'attached/'.substr($amc->attached,0,strpos($amc->attached,'/')));
      }
    }
    BusinessObject:: Delete(true,"");
  }
}
?>
